package mt.ctrl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import mt.business.Cache;
import mt.model.Pricetype;
import mt.model.ShopTheme;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import base.ctrl.BaseController;
import base.jfinal.JsonUtil;
import base.jfinal.anatation.RouteBind;
import base.model.SessionModel;
import mt.Const;

@RouteBind(path = "theme")
public class ThemeCtrl extends BaseController {

	/*
	 * 接收参数： { “area”:”岳麓区”,//选择全部时不要传入该属性值
	 * “name”:”店铺名字”,//文本框输入，文本框没有输入时不要传入该属性值 “size”:”1”,//1:小型密室（1间房）
	 * 2:中型密室（2-3间）3:大型密室（3-5间）4:超级密室（>5间） “content”:”1”,// 1:越狱类 2:恐怖类 3:中国风
	 * 4:谍战类 5:盗墓类 6:科幻类 7:动漫类 8:其他 “category”:”1”,// 1:逻辑密室 2:机关密室 3:剧情密室
	 * 4:大型机械密室 “order”:”1”//排序 } 返回结果： { “shopName”:”店铺名字”, “area”:”岳麓区”,
	 * “street”:”详细地址”, “themeId”:””,//主题ID，查看主题详情时需要用到 “themeName”:””,//主题名字
	 * “size”:”1”,//1:小型密室（1间房） 2:中型密室（2-3间）3:大型密室（3-5间）4:超级密室（>5间）
	 * “content”:”1”,// 1:越狱类 2:恐怖类 3:中国风 4:谍战类 5:盗墓类 6:科幻类 7:动漫类 8:其他
	 * “category”:”1”,// 1:逻辑密室 2:机关密室 3:剧情密室 4:大型机械密室 “minimum”:”3”,// 最少玩家数
	 * “price”:”30”,//售价 “soldNum”:”321”,//已售数量
	 * “coverImg”:”http://xxx.jpg”//主题封面图片 } sql： select
	 * mts.shopName,mts.area,mts
	 * .street,mtt.themeId,mtt.themeName,mtt.size,mtt.content
	 * ,mtt.category,mtt.minimum,mtt.price,mtt.soldNum,mtt.coverImg from mt_shop
	 * mts,mt_theme mtt where mtt.shopId = mts.shopId
	 */
	public void find() {
		// this.renderJson(getDBListToJson("theme.find", this.getParas()));

		String selectSql = "select mts.shopid,mts.shopname,mts.area,mts.street,mtt.themeid,mtt.themename,mtt.evalstar,mtt.size,mtt.content,mtt.category,mtt.minimum,mtt.price,mtt.soldnum,mtt.coverimg,mtt.photo";
		List<Record> list = Db.paginate(getParaToInt("page", 1),
				getParaToInt("pagesize", 10), selectSql,
				getSql("theme.find", getParas())).getList();
		if (list != null) {
			for (Record record : list) {
				BigDecimal price = record.getBigDecimal("price");
				record.getColumns().put("displayprice",
						price != null ? price.divide(new BigDecimal(100)) : 0);
			}
		}

		this.renderJson((new JsonUtil(list)).toString());
	}

	// 获取收藏主题
	public void getTheme(){
		String code = getPara("code", "");
		int userId = Cache.GetUserVOByCode(code).getUserId();
		String selectSql = "SELECT muf.userid,muf.themeid,mu.themename,mu.photo,mu.content,mu.price,mu.soldnum,mu.evalstar,mu.coverimg,mtt.street,mtt.area,mtt.shopname,mtt.shopid "
				+ "FROM mt_user_favorites_theme muf,mt_theme mu,mt_shop mtt,mt_user mt WHERE muf.userid=mt.userid and mu.themeid=muf.themeid and mu.shopid=mtt.shopid and mt.userid=?;";
		List<Record> list = Db.find(selectSql, userId);
		if (list != null) {
			for (Record record : list) {
				BigDecimal price = record.getBigDecimal("price");
				record.getColumns().put("displayprice",
						price != null ? price.divide(new BigDecimal(100)) : 0);
			}
		}

		this.renderJson((new JsonUtil(list)).toString());
	}

	// 用于APP调用
	public void getById() {
		/**
		 * select mts.shopid,mts.shopname,mts.area,mts.street,mts.phone,
		 * mtt.themeid
		 * ,mtt.themename,mtt.size,mtt.content,mtt.category,mtt.diffstar
		 * ,mtt.logicstar,mtt.actionstar,mtt.scenestar,
		 * mtt.minimum,mtt.rewardcash
		 * ,mtt.rewardfree,mtt.experience,mtt.price,mtt.soldnum,mtt.photo
		 **/
		Record record = getDBRecord("theme.getById", this.getParas());
		BigDecimal price = record.getBigDecimal("price");
		record.getColumns().put("displayprice",
				price != null ? price.divide(new BigDecimal(100)) : 0);
		JsonUtil result = new JsonUtil(record, "photo");
		this.renderJson(result.toString());
	}


	//取得主题信息
	public void getShopThemeInfo(){
		int shopId = ((SessionModel)this.getSessionAttr("SessionModel")).getShopId();
		Map<String, Object> map= getParas();
		map.put("shopid", shopId);
		System.out.println(map);
		List<Record> lst=Db.find("select mt_theme.coverImg,themeId,themeName,mt_theme.shopId,shopName,case when size=1 then '小型密室（1间房）' when size=2 then '中型密室（2-3间）' when size=3 then '大型密室（3-5间）' else '超级密室（>5间）' end size ," +
				"case when content=1 then '越狱类' when content=2 then '恐怖类' when content=3 then '中国风' when content=4 then '谍战类' when content=5 then '盗墓类' when content=6 then '科幻类' when content=7 then '动漫类' else '其他' end content," +
				"case when category=1 then '逻辑密室' when category=2 then '机械密室' when category=3 then '剧情密室' else '大型机械密室' end category," +
				"minimum,diffStar,logicStar,actionStar,sceneStar,rewardCash,rewardFree,endDate,remark,rewardDate,experience,mt_theme.status "
				+getSql("theme.getTheme",map));
		JsonUtil json=new JsonUtil(lst);
		this.renderJson(json.toString());
	}

	public void getThemeInfo(){
		Record lst=Db.findFirst("select themeId,themename,size,minimum,content,diffStar,logicStar,category," +
				"actionStar,sceneStar,rewardCash,rewardFree,endDate,status,priceType,price,rewardDate " +
				"from mt_theme where themeId=?",getPara("themeId",""));
		JsonUtil json=new JsonUtil(lst.toJson());
		this.renderJson(json.toString());
	}
	public void priceStr(){
		List<Record> demoList = Db.find("select minPlayer,maxPlayer,price from mt_theme_rate where themeId=? order by minPlayer desc",getParaToInt("themeId",0));
		String pricestr="";
		for(int i = 0; i < demoList.size(); i++){
			Record sum = demoList.get(i);
			String pricetype=sum.get("minPlayer")+"-"+sum.get("maxPlayer")+"人:"+sum.get("price")+"元";
			pricestr = pricetype +";"+pricestr ;
		}
		JsonUtil json=new JsonUtil();
		json.put("pricestr", pricestr);
		this.renderJson(json.toString());
	}


	@Before(Tx.class)
	public void createShopTheme(){
		
		// params 
		
		// validate
		
		long price = 0;
		
		
		int shopId = ((SessionModel)this.getSessionAttr("SessionModel")).getShopId();
		Map<String, Object> map= getParas();
		ShopTheme shoptheme = new ShopTheme();
		shoptheme.set("shopid",shopId);
		shoptheme.setAttrs(map);
		shoptheme.set("price",new BigDecimal(price));
		shoptheme.save();
		Integer themeId = shoptheme.getInt("themeid");
		// 设置包场价
		Db.update("update mt_theme_rate set themeId=? where themeId = 0 ",
				themeId);
		this.renderJson("{\"err\":0}");
	}
	
	@Before(Tx.class)
	public void modifyShopTheme() {
		ShopTheme theme = ShopTheme.dao.findById(this.getPara("themeId"));
		theme.setAttrs(this.getParas()).update();
		this.renderJson(Const.MSG_SUCCESS);
	}
	//删除主题
	@Before(Tx.class)
	public void deleteTheme(){
		Db.update("update mt_theme set status=1 where themeId = ? ",
				getPara("themeId", ""));
		this.renderJson(Const.MSG_SUCCESS);
	}
	//恢复主题
	@Before(Tx.class)
	public void recoverTheme(){
		Db.update("update mt_theme set status=0 where themeId = ? ",
				getPara("themeId", ""));
		this.renderJson(Const.MSG_SUCCESS);
	}

	/** 通过id取得数据 */
	public void getThemeInfoById() {
		ShopTheme shopTheme = ShopTheme.dao.findById(this.getPara("id"));

		this.renderJson(shopTheme);
	}
}
